const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
const path = require("path");
const apiMocker = require("mocker-api");
console.log("env: ", process.env.NODE_ENV);
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
const isDev = process.env.NODE_ENV === "development";
const BundleAnalyzerPlugin =
  require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const DashboardPlugin = require("webpack-dashboard/plugin");

const config = {
  devServer: {
    contentBase: path.resolve(__dirname, "dist"),
    port: "5300", //默认是8080
    quiet: false, //默认不启用
    inline: true, //默认开启 inline 模式，如果设置为false,开启 iframe 模式
    stats: "errors-only", //终端仅打印 error
    overlay: true, //默认不启用
    clientLogLevel: "silent", //日志等级
    compress: true, //是否启用 gzip 压缩,
    hot: true, // 热更新
    proxy: {
      // '/user': 'http://localhost:8300'  // 直接用后端接口的路径匹配
      // 后端接口没有'/api'时
      "/api": {
        target: "http://localhost:8300",
        pathRewrite: {
          "/api": "",
        },
      },
    },
    // 简单模拟数据
    // before(app) {
    //   app.get('/user', (req, res) => {
    //     res.json({name: 'webpack'})
    //   })
    // }
    // mocker-api模拟数据 `npm i mocker-api -D`
    before(app) {
      apiMocker(app, path.resolve("./mock/mocker.js"));
    },
  },
  entry: "./src/main.jsx",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: isDev ? "[name].js" : "[name].[hash:8].js",
    publicPath: "/", //isDev ? '/' : '//sunyxq.top/blog/'
  },
  devtool: "cheap-module-eval-source-map",
  mode: isDev ? "development" : "production",
  resolve: {
    modules: ["./src/components", "node_modules"], //从左到右依次查找
    alias: {
      "@": path.resolve(__dirname, "src"),
      "@components": path.resolve(__dirname, "src/components"),
      "@utils": path.resolve(__dirname, "src/utils"),
    },
    extensions: [".jsx", ".js"],
    // enforceExtension: true,  // 为true时导入语句不能缺省文件后缀。
  },
  externals: {
    // 将一些JS文件存储在 CDN 上(减少 Webpack打包出来的 js 体积)，在 index.html 中通过 <script> 标签引入
    // 仍然可以通过 import 的方式去引用(如 import $ from 'jquery')，并且希望 webpack 不会对其进行打包
    jquery: "jQuery",
  },
  performance: {
    hints: "warning", // 枚举
    maxAssetSize: 30000000, // 整数类型（以字节为单位）
    maxEntrypointSize: 50000000, // 整数类型（以字节为单位）
    assetFilter(assetFilename) {
      // 提供资源文件名的断言函数
      return assetFilename.endsWith(".css") || assetFilename.endsWith(".js");
    },
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          // 'thread-loader',
          // 'cache-loader',
          {
            loader: "babel-loader",
            // 只打算给 babel-loader 配置 cache 的话，也可以不使用 cache-loader，给 babel-loader 增加选项 cacheDirectory
            // 开启 babel-loader的缓存和配置 cache-loader，构建时间很接近
            // options: {
            //   cacheDirectory: true
            // }
          },
        ],
      },
      {
        test: /\.(png|jpeg|gif|jpg|webp|svg)/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 1024 * 10, // 10k
              esModule: false,
              name: "[name]_[hash:6].[ext]",
              outputPath: "assets",
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.(sc|c)ss$/,
        exclude: /node_modules/,
        use: [
          // 'style-loader',
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: isDev,
              reloadAll: true,
            },
          },
          {
            loader: "css-loader",
            options: {
              importLoaders: 2, //如果sass文件里还引入了另外一个sass文件，另一个文件还会从sass-loader向上解析。如果不加，就直接从css-loader开始解析。// 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
              // modules: true, //开启css的模块打包。css样式不会和其他模块发生耦合和冲突
            },
          },
          "postcss-loader",
          "sass-loader",
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html",
      filename: "index.html",
      minify: {
        removeAttributeQuotes: false, // 是否去除属性的双引号，
        collapseWhitespace: false, // 是否折叠空白
      },
      //hash: true,      // 是否加上hash，默认false
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: ["**/*", "!dll", "!dll/**"], // 不删除dll目录下的文件
    }),
    new webpack.DllReferencePlugin({
      manifest: path.resolve(__dirname, "dist", "dll", "manifest.json"),
    }),
    new webpack.ProvidePlugin({
      React: "react",
      Component: ["react", "Component"],
      // $: 'jQuery',
      // _get: ['lodash', 'get'],
      // _: 'lodash'
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:6].css",
    }),
    new CopyWebpackPlugin(
      [
        {
          from: "./public/js/*.js",
          to: path.resolve(__dirname, "dist", "js"),
          flatten: true, // 默认false,为true时，只拷贝文件，不会拷贝文件夹路径
        },
      ],
      {
        ignore: ["base.js"], // 过滤某个或某些文件
      }
    ),
    new OptimizeCssAssetsWebpackPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      DEV: JSON.stringify("dev"),
      FLAG: "true",
    }),
    new HardSourceWebpackPlugin(),
    // new BundleAnalyzerPlugin(),
    new DashboardPlugin(),
  ],
};

module.exports = smp.wrap(config);
